import axios from 'axios'
import { useUserStore } from '@/stores/index'

const baseURL = 'http://big-event-vue-api-t.itheima.net'
const instance = axios.create({
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  function (config) {
    const UserStore = useUserStore()
    if (UserStore.token) {
      config.headers.Authorization = UserStore.token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
import router from '@/router'
//import { ElMessage } from 'element-plus'
instance.interceptors.response.use(
  function (response) {
    if (response.data.code === 0) {
      return response
    }
    ElMessage.error(response.data.message || '服务异常')
    return Promise.reject(response.data)
  },
  function (error) {
    if (error.response?.status === 401) {
      router.push('/login')
    }
    ElMessage.error(error.response.data.message || '服务异常')
    return Promise.reject(error)
  }
)

export default instance
export { baseURL }
